<?php
// +----------------------------------------------------------------------
// | Tpli [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Author 荒年 < 931274989@qq.com >
// +----------------------------------------------------------------------
// | Explain 管理员模型
// +----------------------------------------------------------------------
namespace app\base\model;

use think\Model;

class Admin extends Model
{
  public function groupCates()
  {
    //关联角色表 一对一
    return $this->belongsTo('AuthGroup','group_id','id');
  }

  public static function getAdmin()
  {
    if (isset($post['keywords']) and !empty($post['keywords'])) {
      $where['name'] = ['like', '%' . $post['keywords'] . '%'];
    }
    if (isset($post['group_id_id']) and $post['group_id_id'] > 0) {
      $where['group_id_id'] = $post['group_id_id'];
    }
    if(isset($post['create_time']) and !empty($post['create_time'])) {
      $min_time = strtotime($post['create_time']);
      $max_time = $min_time + 24 * 60 * 60;
      $where['create_time'] = [['>=',$min_time],['<=',$max_time]];
    }
    $admin = empty($where) ? self::order('create_time desc')->paginate(20) : self::where($where)->order('create_time desc')->paginate(20,false,['query'=>$post]);
    return $admin;
  }

  public function add($post)
  {
    $post['password'] = password($post['password']);
    $result = $this->allowField(true)->save($post);
    return $result;
  }

  public function edit($post,$id)
  {
    $result = $this->allowField(true)->save($post,['id'=>$id]);
    return $result;
  }

  public function login($data)
  {
    $user = $this->where('nickname',$data['nickname'])->find();
    if($user) {
      if ($user['password'] == password($data['password'])){
        session('admin', $user['id']);
        session('group_id', $user['group_id']);
        $this->where('id',$user['id'])->update(['login_ip' =>  request()->ip(),'login_time' => time()]);
        return ['code' => 1, 'msg' => '登录成功!']; //信息正确
      }else{
        return ['code' => 0, 'msg' => '用户名或者密码错误，重新输入!']; //密码错误
      }
    }else{
      return ['code' => 0, 'msg' => '用户不存在!']; //用户不存在
    }
  }
}
?>